<?php

namespace App\Http\Controllers;

use App\Exports\ProjectBookTitleExport29;
use App\Exports\ProjectBookTitleExport8;
use App\Exports\ProjectBookTitleExportLY;
use App\Models\PartCompany;
use App\Models\Project;
use App\Models\ProjectClassify;
use App\Models\SearchHistory;
use App\Services\AttachmentService;
use App\Services\BaseService;
use App\Services\CommonService;
use App\Services\ProjectSearchService;
use App\Services\ProjectService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * 项目类
 */
class ProjectController extends Controller
{
    public $projectService;

    public function __construct(ProjectService $projectService)
    {
        parent::__construct();
        $this->projectService = $projectService;
    }

    /**
     * 上传PDF  archive_manage_volume
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \OSS\Http\RequestCore_Exception
     * @author: lxk
     * @date: 2024-12-27 13:22
     */
    public function uploadFile(Request $request) : JsonResponse
    {
        $projectId = $request->input('project_id');
        $type = $request->input('type');
        $file = $request->file('file');
        $uploadResult = (new AttachmentService())->upload($file);
        if ($type == 1) {
            $field = 'file_url1';
        } else{
            $field = 'file_url2';
        }
        Project::query()->where('id', $projectId)->update([$field => $uploadResult['file']]);

        return $this->success('', '上传成功！');
    }

    /**
     * 数据列表
     */
    public function index(Request $request)
    {
        $perPage = $request->input('per_page') ?: $this->limit;

        $list = $this->projectService->getList($request, $perPage);

        ProjectService::createProDirectory(); //从仓库下载代码后，如果项目文件夹不存在则自动创建，避免了手动创建文件夹带来的繁琐

        return $this->success($list);
    }

    /**
     * 导出该项目下的全部案卷
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-6-03 13:47
     */
    public function exportBookTitles(Request $request) : JsonResponse
    {
        $projectId         = $request->input('project_id');
        $partCompanyId     = $request->input('part_company_id', 0);
        $projectClassifyId = $request->input('project_classify_id', 0);
        $isHaveChildren    = $request->input('is_have_children', 0);
        $project           = Project::query()->find($projectId);

       if ($partCompanyId) {
            $partCompany = PartCompany::query()->find($partCompanyId);
            $sheetName = $partCompany->title;
            if ($isHaveChildren) {
                $projectClassify = ProjectClassify::query()->find($projectClassifyId);
                CommonService::addActionLog('导出单位工程专业案卷', $projectClassify->title);
                $sheetName = $partCompany->title.'_'.$projectClassify->title;
            } else {
                CommonService::addActionLog('导出参见单位案卷', $partCompany->title);
            }
        } else {
            CommonService::addActionLog('导出项目案卷', $project->title);
            $sheetName = $project->title;
        }
        $combinationId = $this->projectService->getDossierCombination($partCompanyId);
        $fileName = get_valid_path("【{$project->document_number}】{$sheetName}_案卷_") . date('His') . '.xlsx';
        $filePath = "public/excels/$fileName";
        switch ($combinationId) {
            case 2: //8号文格式
                (new ProjectBookTitleExport8($sheetName, $projectId, $partCompanyId, $projectClassifyId))->store($filePath);
                break;
            case 3: //兰渝格式
                (new ProjectBookTitleExportLY($sheetName, $projectId, $partCompanyId, $projectClassifyId))->store($filePath);
                break;
            default: //29号文格式
                (new ProjectBookTitleExport29($sheetName, $projectId, $partCompanyId, $projectClassifyId))->store($filePath);
                break;
        }
        $filePath    = str_replace('public', 'storage', $filePath);
        $downloadUrl = config('site.domain') . $filePath;
        $fileInfo    = pathinfo($downloadUrl);
        $data = [
            'basename'     => $fileInfo['basename'],
            'download_url' => $downloadUrl
        ];

        return $this->success($data);
    }

    /**
     * 创建或修改一个项目
     */
    public function store(Request $request)
    {
        $id = $request->input('id');
        if ($id) {
            $project = Project::query()->find($id);
            if (!is_super_admin() && ($project->creator_id != user_id())) {
                return $this->error('您无权修改！请联系超管');
            }
            if (!$this->projectService->updateData($request->all(), $id)) {
                return $this->error('保存失败');
            }
        } else {
            $result = $this->projectService->saveData($request->all());
            if ($result['msg']) {
                return $this->error($result['msg']);
            }
        }
        return $this->success('', '保存成功！');
    }

    /**
     * 查询单个数据
     */
    public function show(Request $request)
    {
        $id   = $request->input('id');
        $info = ProjectService::getInfo($id);

        return $this->success($info);
    }

    /**
     * 匹配分类模板设置
     */
    function setClassifyTemplateId(Request $request)
    {
        $projectId  = $request->id ?? 0; //项目id
        $templateId = $request->template_id ?? 0; //分类目录模板id
        if (!$this->projectService->setClassifyTemplateId($projectId, $templateId)) {
            return $this->error('保存失败!');
        }

        return $this->success('', '保存成功');
    }

    /**
     * 项目匹配案卷组合
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/5/7 14:32
     */
    public function relateCombination(Request $request) : JsonResponse
    {
        $params = $request->all(['project_id', 'combination_id']);

        if(!$this->projectService->relateCombination($params)){
            return $this->error('操作失败');
        };

        return $this->success('', '操作成功！');
    }

    /**
     * 批量软删除，ids可以是以","逗号分割的字符串，也可以是数组形式
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/5/7 14:32
     */
    public function destroyMore(Request $request) : JsonResponse
    {
        $ids = to_array($request->input('ids'));
        if (!Project::destroy($ids)) {
            return $this->error('删除失败！');
        };

        return $this->success('', '放入回收站成功');
    }

}
